package com.king.designpatterns.hybriddesignpattern.hybriddesignpattern.chainofcommandandresponsibility;

import java.util.ArrayList;
import java.util.List;

/**
 * 抽象类Command
 *
 * 作用：
 *      ■ 定义命令的执行方法；
 *      ■ 负责命令族（责任链）的建立。
 *
 * @author king
 * @date 2021-06-11 14:46
 */
public abstract class Command {
    public abstract String execute(CommandVO vo);

    // 建立链表
    protected final List<? extends CommandName> buildChain(Class<? extends CommandName> abstractClass){
        // 取出所有的命令名下的子类
        List<Class> classes = ClassUtils.getSonClass(abstractClass);

        // 存放命令的实例，并建立链表关系
        List<CommandName> commandNameList = new ArrayList<>();
        for (Class aClass : classes) {
            CommandName commandName = null;
            try {
                commandName = (CommandName) Class.forName(aClass.getName()).newInstance();
            }catch (Exception e){
                e.printStackTrace();
            }
            // 建立链表
            if (commandNameList.size() > 0){
                commandNameList.get(commandNameList.size() - 1).setNext(commandName);
            }
            commandNameList.add(commandName);
        }

        return commandNameList;
    }
}
